//
//  UIAlertView+Extend.m
//  ReviewDemo
//
//  Created by 龙 on 2018/3/14.
//  Copyright © 2018年 long. All rights reserved.
//

#import "UIAlertView+Extend.h"
#import <objc/runtime.h>

@implementation UIAlertView (Extend)

static char kUIAlertViewBlockAddress;
- (void)showAlertWithHandler:(AlertCallBlock)callback
{
    self.delegate = self;
    //第一个参数是主对象，第二个参数是键，第三个参数是关联的对象，第四个参数是存储策略:是枚举，定义了内存管理语义
    objc_setAssociatedObject(self, &kUIAlertViewBlockAddress, callback, OBJC_ASSOCIATION_COPY);
    [self show];
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    //根据给定的键从某对象中获取相应的关联对象值
    AlertCallBlock alertCallBack = objc_getAssociatedObject(self, &kUIAlertViewBlockAddress);
    if (alertCallBack)
    {
        alertCallBack(buttonIndex);
        objc_setAssociatedObject(self, &kUIAlertViewBlockAddress, nil, OBJC_ASSOCIATION_COPY);
    }    
}

@end
